<template>
  <router-view v-if="route.matched.length === 3" @updated="handleUpdated" />
  <e-container v-else :loading="loading">
    <e-title v-permission="'ServicePrice:Add'" title="Service Price Application" />
    <div class="quote-apply">
      <div v-if="!quoteApply" v-permission="'ServicePrice:Add'" class="empty">
        <a-button type="link" size="small" @click="handleClickCreate">
          <a-space><e-icon type="add" />Create Price Change Application</a-space>
        </a-button>
      </div>
      <div v-else v-permission="'ServicePrice:Query'" class="item">
        <a-row>
          <a-col :span="12" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
            <a
              :title="quoteApply.theme"
              :target="quoteApply.id"
              :href="
                router.resolve({
                  name: 'Price',
                  params: { id: quoteApply.id }
                }).href
              ">
              {{ quoteApply.theme }}
            </a>
          </a-col>
          <a-col :span="4">{{ dayjs(quoteApply.createOn).format(DATA_FORMAT) }}</a-col>
          <a-col :span="4">{{ quoteApply.statusName }}</a-col>
          <a-col :span="4">
            <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
              <span v-if="quoteApply.status === 20" :title="quoteApply.bumDisplayName + ' is processing'">
                {{ quoteApply.bumDisplayName }} is processing
              </span>
              <span v-if="quoteApply.status === 25" :title="quoteApply.apDisplayName + 'is processing'">
                {{ quoteApply.apDisplayName }} is processing
              </span>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
    <div v-permission="'ServicePrice:Detail'" class="operations">
      <a-space>
        <e-title title="Negotiated Service Price" />
        <a-divider v-if="quote" type="vertical" />
        <a-button v-if="quote" type="link" size="small" @click="handleExportPrice">
          <a-space class="download">
            <e-icon type="excel" line-height="15px" font-size="18px" default-color />Export All Price Information
          </a-space>
        </a-button>
      </a-space>
      <a-button
        v-if="!quote && !quoteApply"
        v-permission="'ServicePrice:Add'"
        type="link"
        @click="handleClickCreateByQuotation">
        <a-space><e-icon type="SaveCopetoALL" />Create by Quotation</a-space>
      </a-button>
    </div>
    <div v-permission="'ServicePrice:Detail'" class="negotiated">
      <e-empty v-if="!quote" centered>
        <template #description>No Records</template>
      </e-empty>
      <div v-else class="quote">
        <a-list bordered :data-source="quote">
          <template #renderItem="{ item, index }">
            <a-list-item :class="{ deep: index % 2 === 0 }">
              <router-link
                :to="{
                  name: 'negotiatedPrice',
                  params: { id: id, sLang: item.sLang, tLang: item.tLang }
                }">
                <a-space class="language-pair">
                  {{ item.sLangName }}<e-icon type="Fold" font-size="12px" />{{ item.tLangName }}
                </a-space>
              </router-link>
              <span>{{ dayjs(item.operateOn).format(DATA_FORMAT) }}</span>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>
    <a-modal
      v-model:visible="showExistQuotation"
      width="888px"
      title="Create Price By Quotation"
      wrap-class-name="primary-modal quotation-table"
      ok-text="Create"
      :ok-button-props="{ disabled: selectedQuotation.length === 0 }"
      @cancel="showExistQuotation = false"
      @ok="handleCreateByQuotation">
      <a-table
        :row-selection="{ selectedRowKeys: selectedQuotation, type: 'radio', onChange: handleQuotationTableSelect }"
        :columns="existQuotationColumns"
        :data-source="existQuotation"
        :pagination="false"
        row-key="id"
        :loading="existQuotationLoading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'opt'"> </template>
        </template>
        <template #emptyText> <e-empty centered :size="150" :height="240" /> </template>
      </a-table>
    </a-modal>
  </e-container>
</template>

<script setup>
import { inject, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import ServicePrice from '@/api/client/servicePrice.js'
import EEmpty from '@/components/EEmpty.vue'
import { DATA_FORMAT } from '@/constants/date.js'
import Util from '@/utils'
const { Modal, message } = inject('Feedback')
const route = useRoute()
const router = useRouter()
const loading = ref(true)
const { id } = route.params
// 申请单
const quoteApply = ref(null)
// 协议价格
const quote = ref(null)
const loadData = () => {
  loading.value = true
  ServicePrice.getBaseInfo(id)
    .then(({ data }) => {
      quoteApply.value = data.quoteApply
      quote.value = data.quote
    })
    .finally(() => {
      loading.value = false
    })
}
loadData()
const handleClickCreate = () => {
  loading.value = true
  ServicePrice.isAvailableToCreateApply(id)
    .then(({ data }) => {
      if (data) {
        router.push({ name: 'CreateOrEditChangeApplication', params: { id: id } })
      }
    })
    .finally(() => {
      loading.value = false
    })
}
const handleUpdated = () => {
  loadData()
}
const handleExportPrice = () => {
  ServicePrice.exportAllNegotiatedPrice(id).then(res => {
    Util.downloadBlob(res, 'Negotiated-Price.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  })
}
const showExistQuotation = ref(false)
const existQuotationColumns = [
  {
    title: 'Project Name',
    dataIndex: 'projectName',
    key: 'projectName'
  },
  {
    title: 'Client Contact',
    dataIndex: 'clientContact',
    key: 'clientContact'
  },
  {
    title: 'Ver.',
    dataIndex: 'verNum',
    key: 'verNum'
  },
  {
    title: 'Grand Total',
    dataIndex: 'grandTotal',
    key: 'grandTotal'
  },
  {
    title: 'Created By',
    dataIndex: 'displayName',
    key: 'displayName'
  }
]
const selectedQuotation = ref([])
const existQuotation = ref([])
const existQuotationLoading = ref(false)
const handleClickCreateByQuotation = () => {
  ServicePrice.isAvailableToCreateApply(id).then(() => {
    existQuotationLoading.value = true
    ServicePrice.getExistQuotation(id)
      .then(({ data }) => {
        existQuotation.value = data
        if (Array.isArray(existQuotation.value) && existQuotation.value.length) {
          selectedQuotation.value = [existQuotation.value[0].id]
        }
      })
      .finally(() => {
        existQuotationLoading.value = false
      })
    showExistQuotation.value = true
  })
}
const handleCreateByQuotation = () => {
  if (selectedQuotation.value.length > 0) {
    Modal.confirm({
      content: 'Sure to create from quotation ?',
      onOk: () => {
        ServicePrice.createFromQuotation(id, selectedQuotation.value[0]).then(({ data }) => {
          loadData()
          showExistQuotation.value = false
        })
      }
    })
  } else {
    message.warning('Please select a record !')
  }
}
const handleQuotationTableSelect = selectedRowKeys => {
  selectedQuotation.value = selectedRowKeys
}
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_table';
.quote-apply {
  .empty {
    height: 48px;
    background-color: @gray;
    margin: 24px 12px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .item {
    height: 48px;
    border: 1px solid @gray;
    line-height: 48px;
    margin: 24px 0;
    padding: 0 16px;
  }
}
.operations {
  display: flex;
  justify-content: space-between;
}
.quote {
  padding: 24px 0;
  .language-pair {
    color: @primary-color;
  }
  .deep {
    background-color: @milk;
  }
}
.download {
  .e-icon {
    vertical-align: text-top;
  }
}
</style>
<route lang="yaml">
name: Service Price
path: '/client/:id/service-price'
meta:
  sort: 80
  title: Service Price
  icon: Service_Price
  permission: ServicePrice
</route>
